package gfx.layers;

import gui.components.Viewport;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.swing.ListModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;

public class LayerManager implements ListModel{
	private List<Layer> layerList;
	private Set<ListDataListener> listListeners;
	private Viewport viewport;
	
	
	public LayerManager(){
		layerList = new ArrayList<Layer>();
		listListeners = new HashSet<ListDataListener>();
  }
	
	public Layer addLayer(File file){
		Layer newLayer = new Layer(file, "Layer" + layerList.size(), this);
		return addLayer(newLayer);
	}
	
	public Layer addLayer(Layer layer){
		layerList.add(layer);
		for(ListDataListener l : listListeners){
			l.intervalAdded(new ListDataEvent(this, ListDataEvent.INTERVAL_ADDED, layerList.size() - 1, layerList.size()));
		}
		return layer;
	}
	
	public void dropLayer(Layer layer){
		layerList.remove(layer);
		for(ListDataListener l : listListeners){
			l.intervalRemoved(new ListDataEvent(this, ListDataEvent.INTERVAL_REMOVED, layerList.size(), layerList.size() + 1));
		}
	}
	
	public void layerHasChanged(Layer layer){
		int layerIndex = layerList.indexOf(layer);
		
		for(ListDataListener l : listListeners){			
			l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, layerIndex, layerIndex + 1));
		}
	}
	
	public void setViewport(Viewport viewport){
		this.viewport = viewport;
	}
	
	public void showLayerInViewport(Layer layer){
		if(viewport != null){
			viewport.setImage(layer.getImage());
			viewport.repaint();
		}
	}

	@Override
  public int getSize() {
	  return layerList.size();
  }

	@Override
  public Object getElementAt(int index) {
	  return layerList.get(index);
  }

	@Override
  public void addListDataListener(ListDataListener l) {
		listListeners.add(l);
  }

	@Override
  public void removeListDataListener(ListDataListener l) {
		listListeners.remove(l);
  }
}
